package com.xci.platform.helper;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class CookieHelper {
    /**
     * 获取Cookie
     */
    public static Cookie[] getCookies() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request;
        if (attributes != null) {
            request = attributes.getRequest();
            return request.getCookies();
        }
        return new Cookie[0];
    }

    /**
     * 获取cookie
     */
    public static String getCookie(String name) {
        try {
            Cookie[] cookies = getCookies();
            for (int i = 0; i < (cookies == null ? 0 : cookies.length); i++) {
                if ((name).equalsIgnoreCase(cookies[i].getName())) {
                    return URLDecoder.decode(cookies[i].getValue(), "UTF-8");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置 Cookie
     */
    public static void setCookie(Cookie cookie) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response;
        if (attributes != null) {
            response = attributes.getResponse();
            if (response != null) {
                response.addCookie(cookie);
            }
        }
    }

    /**
     * 设置 Cookie
     */
    public static void setCookie(String name, String value) {
        try {
            String v = URLEncoder.encode(value, "UTF-8");
            Cookie cookie = new Cookie(name, v);
            cookie.setPath("/");
            setCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除cookie
     */
    public static void removeCookie(String name) {
        try {
            Cookie[] cookies = getCookies();
            for (int i = 0; i < (cookies == null ? 0 : cookies.length); i++) {
                if ((name).equalsIgnoreCase(cookies[i].getName())) {
                    Cookie cookie = new Cookie(name, "");
                    cookie.setPath("/");
                    cookie.setMaxAge(0);// 设置保存cookie最大时长为0，即使其失效
                    setCookie(cookie);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
